package com.cj.sbs.base.exception;

import com.cj.sbs.base.ReturnCodeEnum;
import com.cj.sbs.base.ReturnData;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName: ExceptionController <br/>
 * Function: 全局异常处理器 <br/>
 * date: 2018/04/25 15:38 <br/>
 *
 * @author chenj
 * @version 1.0.0
 * @since JDK 1.8
 */
@RestControllerAdvice
public class ExceptionController {

    /**
     * hibernate validate 参数异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(BindException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ReturnData<String> validationExceptionHandler(BindException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        String errorMsg = "";
        if (bindingResult != null && !CollectionUtils.isEmpty(bindingResult.getAllErrors())) {
            errorMsg = bindingResult.getAllErrors().get(0).getDefaultMessage();
        }
        return ReturnData.fail(ReturnCodeEnum.PARAM_ERROR, errorMsg);
    }

    /**
     * 参数校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(SbsException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ReturnData sbsExceptionHandler(SbsException ex) {
        return ReturnData.fail(ex.getReturnCode());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public ReturnData<Void> authenticationExceptionHandler(AuthenticationException ex) {
        return ReturnData.fail(ReturnCodeEnum.USER_ACOUNT_ERROR);
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthorizedException.class)
    public ReturnData<Void> unauthorizedExceptionHandler(AuthenticationException ex) {
        return ReturnData.fail(ReturnCodeEnum.USER_NO_AUTH);
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ReturnData<Void> globalException(HttpServletRequest request, Throwable ex) {
        return ReturnData.fail(ReturnCodeEnum.INTERNAL_ERROR);
    }
}
